﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using cn.school.Models.Res;
using cn.school.Models.Exceptions;

namespace cn.school.Restful.Filter;

public class ExceptionFilter : IActionFilter, IOrderedFilter
{
    private readonly ILogger<ExceptionFilter> _logger;

    public ExceptionFilter(ILogger<ExceptionFilter> logger)
    {
        _logger = logger;
    }

    public int Order => int.MaxValue - 10;

    public void OnActionExecuting(ActionExecutingContext context)
    {

    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        var res = new CommonResponse();
        if (context.Exception == null)
        {
            return;
        }

        if (context.Exception is LogicException logicException)
        {
            res.Message = logicException.GetMessage();
            res.Code = logicException.GetCode();
            goto Handler;
        }

        if (context.Exception is ArgumentException argumentException)
        {
            res.Data = null;
            res.Message = argumentException.Message;
            res.Code = 400;
            goto Handler;
        }

    Handler:
        res.Data = null;
        context.Result = new ObjectResult(res) { StatusCode = 200 };
        context.ExceptionHandled = true;
        _logger.LogError(context.Exception.Message);
        _logger.LogError(context.Exception.StackTrace);
    }
}